# coding=utf-8
#

"""
redis连接的封装
"""

import json
import redis

from iminer.sm_log import getLogger

from django.conf import settings


logger = getLogger("iminer.utils.redis")


class RedisProxy(object):

    def __init__(self, host: str = settings.REDIS_HOST,
                       port: int = settings.REDIS_PORT,
                       db: int = settings.REDIS_DB):

        # 初始化redis连接池
        self.redis_pool = redis.ConnectionPool(host=host,
                                               port=port,
                                               db=db)

        self.r = redis.StrictRedis(connection_pool=self.redis_pool)

    def set_key(self, key: str, val: object, expire_time: int = 10) -> None:
        """
        将值放到对应的Key上

        Args:
            :params: key(str): key
            :params: val(object): 值
            :params: expire_time(int): 超时时间

        Returns:
            None
        """
        self.r.set(key, val)

        # 如果指定了超时时间，那么就设置上，如果为0，则表示不超时
        if expire_time:
            self.r.expire(key, expire_time)

    def get_key(self, key: str) -> object:
        """
        从指定的key中获取数据

        Args:
            :params: key(str): 需要获取数据的key

        Returns:
            val
        """
        return self.r.get(key)


redis_proxy = RedisProxy()

